package com.xiaoxu.springboot.modules.common.service.impl;

import com.xiaoxu.springboot.config.ResourceConfigBean;
import com.xiaoxu.springboot.modules.common.service.ImageService;
import com.xiaoxu.springboot.modules.common.vo.Result;
import com.xiaoxu.springboot.utils.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;


@Service
public class ImageServiceImpl implements ImageService {
    public final static Logger LOGGER= LoggerFactory.getLogger(ImageServiceImpl.class);
    @Autowired
    private ResourceConfigBean resourceConfigBean;
    @Value("${project.artifactId}")
    private String artifactId;

    @Override
    public Result<String> uploadImage(MultipartFile file, String imageTypeName) {
        //判断图片是否为空
        if (file.isEmpty()){
            return new Result<>(Result.ResultStatus.FAILD.code,"文件为空");

        }

        //对图片进行校验
        if (!FileUtil.isImage(file)){
            return new Result<>(Result.ResultStatus.FAILD.code,
                    "请选择一个图片");
        }

        //图片重命名
        String imageName=String.format("%s.%s",
                System.currentTimeMillis(),
                FileUtil.getFileType(file.getOriginalFilename()));

        //构建目标文件夹，如果不存在则创建
        String destFolder=String.format("%s%s/%s",
                System.getProperty("os.name").toLowerCase().startsWith("win")?
                        resourceConfigBean.getLocalPathForWindow():
                        resourceConfigBean.getLocalPathForLinux(),
                artifactId,
                imageTypeName);
        File destFolderFile=new File(destFolder);
        if (!destFolderFile.exists()){
            destFolderFile.mkdirs();
        }

        //构造图片存放的绝对路径
        String destPath=String.format("%%s/%s", destFolder,imageName);

        //构造图片相对路径
        String relativePath=String.format("%s%s/%s/%s",
                resourceConfigBean.getResourcePath(),
                artifactId,
                imageTypeName,
                imageName);

        //保存图片
        try {
            file.transferTo(new File(destPath));
        } catch (IOException e) {
            e.printStackTrace();
            LOGGER.info(e.getMessage());
            return new Result<>(Result.ResultStatus.FAILD.code,"error");
        }

        //返回结果集
        return new Result<>(Result.ResultStatus.SUCCESS.code,"Upload image is success");
    }
}
